<template>
	<view class="page-container">
		<!-- 顶部标题栏 -->
		<view class="page-header">
			<view class="header-left">
				<text class="page-title">医院管理</text>
				<text class="page-subtitle">单一医院系统 - 查看和管理医院基本信息</text>
			</view>
			</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-state">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 空状态：未创建医院 -->
		<view v-else-if="!hospital" class="empty-state">
			<text class="empty-icon">🏥</text>
			<text class="empty-title">尚未创建医院信息</text>
			<text class="empty-text">单一医院系统需要先创建医院基本信息才能使用其他功能</text>
			<button class="btn btn-primary btn-large" @click="handleCreate">
				<text class="icon">+</text> 立即创建医院
			</button>
		</view>

		<!-- 医院信息卡片 -->
		<view v-else class="hospital-card">
			<!-- 医院Banner -->
			<view v-if="getImageUrl(hospital.banner)" class="hospital-banner">
				<image 
					:src="getImageUrl(hospital.banner)" 
					mode="aspectFill"
					class="banner-image"
				/>
			</view>
			
			<!-- 医院基本信息 -->
			<view class="hospital-header">
				<view class="hospital-logo-wrapper">
					<image 
						v-if="getImageUrl(hospital.logo)"
						:src="getImageUrl(hospital.logo)" 
						mode="aspectFill"
						class="hospital-logo"
					/>
					<view v-else class="hospital-logo-placeholder">
						<text class="placeholder-icon">🏥</text>
			</view>
		</view>
				<view class="hospital-info">
					<text class="hospital-name">{{ hospital.hospital_name }}</text>
					<view class="hospital-rating">
						<text class="rating-value">{{ hospital.rating || 0 }}</text>
						<text class="rating-stars">⭐</text>
						<text class="rating-count">({{ hospital.total_reviews || 0 }}条评价)</text>
			</view>
		</view>
			</view>

			<!-- 医院详细信息 -->
			<view class="hospital-body">
				<view class="info-section">
					<text class="section-title">基本信息</text>
					<view class="info-row">
						<text class="info-label">📍 地址</text>
						<text class="info-value">{{ hospital.address || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">📞 电话</text>
						<text class="info-value">{{ hospital.phone || '-' }}</text>
			</view>
					<view v-if="hospital.introduction" class="info-row vertical">
						<text class="info-label">📝 医院介绍</text>
						<text class="info-value">{{ hospital.introduction }}</text>
					</view>
			</view>

				<view class="info-section">
					<text class="section-title">营业信息</text>
					<view class="info-row">
						<text class="info-label">🕐 营业时间</text>
						<text class="info-value">{{ getWorkingHoursDisplay() }}</text>
					</view>
				</view>

				<view v-if="hospital.parking_info || hospital.public_transport" class="info-section">
					<text class="section-title">交通信息</text>
					<view v-if="hospital.parking_info" class="info-row">
						<text class="info-label">🅿️ 停车信息</text>
						<text class="info-value">{{ hospital.parking_info }}</text>
					</view>
					<view v-if="hospital.public_transport" class="info-row">
						<text class="info-label">🚌 公交信息</text>
						<text class="info-value">{{ hospital.public_transport }}</text>
					</view>
					</view>

				<view class="info-section">
					<text class="section-title">证照信息</text>
					<view class="info-row">
						<text class="info-label">📄 营业执照号</text>
						<text class="info-value">{{ hospital.business_license || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">🏥 医疗许可证号</text>
						<text class="info-value">{{ hospital.medical_license || '-' }}</text>
					</view>
					</view>

				<view class="info-section">
					<text class="section-title">系统信息</text>
					<view class="info-row">
						<text class="info-label">创建时间</text>
						<text class="info-value">{{ formatTime(hospital.create_time) }}</text>
			</view>
					<view class="info-row">
						<text class="info-label">更新时间</text>
						<text class="info-value">{{ formatTime(hospital.update_time) }}</text>
				</view>
			</view>
		</view>

			<!-- 操作按钮 -->
			<view class="hospital-actions">
				<button class="btn btn-primary" @click="handleEdit">
					<text class="icon">✏️</text> 编辑医院信息
				</button>
				<button class="btn btn-danger" @click="handleDelete">
					<text class="icon">🗑️</text> 删除医院
				</button>
				</view>
			</view>

		<!-- 提示卡片 -->
		<view class="tip-card">
			<text class="tip-icon">💡</text>
			<view class="tip-content">
				<text class="tip-title">单一医院系统说明</text>
				<text class="tip-text">本系统为单一医院设计，仅支持管理一家医院的信息。所有业务数据（医生、护士、患者等）将自动关联到此医院。</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const loading = ref(true)
const hospital = ref(null)

onMounted(() => {
	loadHospital()
})

// 加载医院信息
async function loadHospital() {
	loading.value = true
	try {
		const hospitalService = uniCloud.importObject('dh-hospital-service')
		const result = await hospitalService.getHospitalInfo()
		
		if (result.code === 200) {
			hospital.value = result.data
		} else if (result.code === 404) {
			// 医院不存在
			hospital.value = null
		} else {
			uni.showToast({ title: result.message || '加载失败', icon: 'none' })
		}
	} catch (error) {
		console.error('加载医院信息失败:', error)
		uni.showToast({ title: error.message || '加载失败', icon: 'none' })
	} finally {
		loading.value = false
	}
}

// 创建医院
function handleCreate() {
	uni.navigateTo({
		url: '/pages/business/hospitals/add'
	})
}

// 编辑医院
function handleEdit() {
	if (!hospital.value) return
	uni.navigateTo({
		url: `/pages/business/hospitals/edit?id=${hospital.value._id}`
	})
}

// 删除医院
async function handleDelete() {
	if (!hospital.value) return
	
	try {
		// 第一步：检查是否有关联数据
		uni.showLoading({ title: '检查关联数据...' })
		const db = uniCloud.database()
		
		const relatedCounts = {
			doctors: 0,
			nurses: 0,
			patients: 0,
			services: 0,
			products: 0
}

		// 并行查询所有关联表的数据量
		const [doctorsRes, nursesRes, patientsRes, servicesRes, productsRes] = await Promise.all([
			db.collection('dh-doctors').where({ hospital_id: hospital.value._id }).count(),
			db.collection('dh-nurses').where({ hospital_id: hospital.value._id }).count(),
			db.collection('dh-patients').where({ hospital_id: hospital.value._id }).count(),
			db.collection('dh-services').where({ hospital_id: hospital.value._id }).count(),
			db.collection('dh-products').where({ hospital_id: hospital.value._id }).count()
		])
		
		relatedCounts.doctors = doctorsRes.total || 0
		relatedCounts.nurses = nursesRes.total || 0
		relatedCounts.patients = patientsRes.total || 0
		relatedCounts.services = servicesRes.total || 0
		relatedCounts.products = productsRes.total || 0
		
		const totalRelated = Object.values(relatedCounts).reduce((sum, count) => sum + count, 0)
		
		uni.hideLoading()
		
		// 第二步：如果有关联数据，给出详细提示
		if (totalRelated > 0) {
			let warningMessage = `系统中存在关联数据，删除医院后这些数据将失去医院关联：\n\n`
			if (relatedCounts.doctors > 0) warningMessage += `• ${relatedCounts.doctors} 名医生\n`
			if (relatedCounts.nurses > 0) warningMessage += `• ${relatedCounts.nurses} 名护士\n`
			if (relatedCounts.patients > 0) warningMessage += `• ${relatedCounts.patients} 名患者\n`
			if (relatedCounts.services > 0) warningMessage += `• ${relatedCounts.services} 项服务\n`
			if (relatedCounts.products > 0) warningMessage += `• ${relatedCounts.products} 个产品\n`
			warningMessage += `\n建议：先删除或转移这些数据后再删除医院。`
			
			uni.showModal({
				title: '存在关联数据',
				content: warningMessage,
				showCancel: true,
				cancelText: '取消删除',
				confirmText: '仍要删除',
				confirmColor: '#ef4444',
				success: (modalRes) => {
					if (modalRes.confirm) {
						confirmDeleteHospital()
		}
				}
			})
	} else {
			// 没有关联数据，直接确认删除
			uni.showModal({
				title: '确认删除',
				content: '确定要删除医院信息吗？此操作不可撤销！',
				confirmText: '确认删除',
				confirmColor: '#ef4444',
				success: (modalRes) => {
					if (modalRes.confirm) {
						confirmDeleteHospital()
		}
	}
			})
		}
	} catch (err) {
		console.error('检查关联数据失败:', err)
		uni.hideLoading()
		uni.showToast({ 
			title: '检查失败：' + (err.message || '未知错误'), 
			icon: 'none' 
		})
	}
}

// 确认删除医院（包含云存储文件清理）
async function confirmDeleteHospital() {
	try {
		uni.showLoading({ title: '删除中...' })
		
		// 1. 提取要删除的云存储文件ID
		const filesToDelete = []
		if (hospital.value.logo && hospital.value.logo.url) {
			filesToDelete.push(hospital.value.logo.url)
}

		console.log('准备删除的文件:', filesToDelete)
		
		// 2. 调用云对象方法软删除医院记录（会处理云存储文件）
		const hospitalsObj = uniCloud.importObject('dh-hospitals')
		await hospitalsObj.deleteHospital(hospital.value._id, '管理后台删除')
		
		// 3. 删除云存储文件（云对象已处理，这里保留作为备份）
		if (filesToDelete.length > 0) {
			try {
				const deleteResult = await uniCloud.deleteFile({
					fileList: filesToDelete
				})
				console.log('云存储文件删除结果:', deleteResult)
				
				if (deleteResult.fileList && deleteResult.fileList.length > 0) {
					const failedFiles = deleteResult.fileList.filter(f => f.code !== 0)
					if (failedFiles.length > 0) {
						console.warn('部分文件删除失败:', failedFiles)
					}
				}
			} catch (fileErr) {
				console.error('删除云存储文件失败:', fileErr)
				// 文件删除失败不影响整体流程，只记录日志
			}
		}
		
		uni.hideLoading()
					uni.showToast({ 
						title: '医院已移至回收站', 
						icon: 'success' 
					})
					
					// 刷新页面
					setTimeout(() => {
						loadHospital()
					}, 1500)
	} catch (err) {
		console.error('删除医院失败:', err)
		uni.hideLoading()
		uni.showToast({ 
			title: err.message || '删除失败', 
			icon: 'none' 
		})
	}
}

// 格式化营业时间显示
function formatWorkingHours(hospital) {
	if (!hospital) return '-'
	
	const { working_hours_start, working_hours_end, closed_days, holiday_closed } = hospital
	
	// 基本时间
	const timeRange = `${working_hours_start || '08:00'} - ${working_hours_end || '18:00'}`
	
	// 计算工作日
	const allDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
	const closedDaysArray = closed_days || []
	const workingDays = allDays.filter(day => !closedDaysArray.includes(day))
	
	// 如果没有休息日，显示全周
	if (workingDays.length === 7) {
		const holidayText = holiday_closed === false ? '，节假日营业' : '，法定节假日除外'
		return `全周 ${timeRange}${holidayText}`
	}
	
	// 如果有休息日，计算连续工作日范围
	const workingRange = getWorkingDaysRange(workingDays)
	const holidayText = holiday_closed === false ? '，节假日营业' : '，法定节假日除外'
	
	return `${workingRange} ${timeRange}${holidayText}`
}

// 计算工作日范围
function getWorkingDaysRange(workingDays) {
	if (workingDays.length === 0) return '暂无营业日'
	if (workingDays.length === 1) return workingDays[0]
	
	// 检查是否是连续的工作日
	const dayOrder = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
	const indices = workingDays.map(day => dayOrder.indexOf(day)).sort((a, b) => a - b)
	
	// 检查是否连续
	let isContinuous = true
	for (let i = 1; i < indices.length; i++) {
		if (indices[i] - indices[i-1] !== 1) {
			isContinuous = false
			break
	}
}

	if (isContinuous) {
		// 连续工作日，显示范围
		const firstDay = dayOrder[indices[0]]
		const lastDay = dayOrder[indices[indices.length - 1]]
		return `${firstDay}至${lastDay}`
	} else {
		// 非连续，列举所有工作日
		return workingDays.join('、')
	}
}

// 提取图片URL
function getImageUrl(imageData) {
	if (!imageData) return ''
	if (typeof imageData === 'string') return imageData
	if (typeof imageData === 'object' && imageData.url) return imageData.url
	if (Array.isArray(imageData) && imageData.length > 0) {
		const first = imageData[0]
		return typeof first === 'string' ? first : (first.url || '')
	}
	return ''
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 获取营业时间显示
function getWorkingHoursDisplay() {
  if (!hospital.value) return '-'
  return formatWorkingHours(hospital.value)
}
</script>

<style scoped lang="scss">
.page-container {
	padding: 20px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
	background: white;
	padding: 20px;
	border-radius: 12px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-left {
	display: flex;
	flex-direction: column;
}

.page-title {
	font-size: 24px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 4px;
}

.page-subtitle {
	font-size: 14px;
	color: #6b7280;
}

/* 加载状态 */
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
	background: white;
	border-radius: 12px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}

.loading-spinner {
	width: 40px;
	height: 40px;
	border: 4px solid #e5e7eb;
	border-top-color: #3b82f6;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 16px;
}

@keyframes spin {
	to { transform: rotate(360deg); }
	}

.loading-text {
	font-size: 14px;
	color: #6b7280;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
	background: white;
	border-radius: 12px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.empty-icon {
	font-size: 64px;
	margin-bottom: 16px;
}

.empty-title {
	font-size: 18px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 8px;
}

.empty-text {
	font-size: 14px;
	color: #6b7280;
	margin-bottom: 24px;
	text-align: center;
	max-width: 400px;
	line-height: 1.6;
	}

/* 医院卡片 */
.hospital-card {
	background: white;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	margin-bottom: 20px;
}

.hospital-banner {
	width: 100%;
	height: 200px;
	overflow: hidden;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.banner-image {
	width: 100%;
	height: 100%;
}

.hospital-header {
	display: flex;
	align-items: center;
	padding: 24px;
	gap: 20px;
	border-bottom: 1px solid #e5e7eb;
}

.hospital-logo-wrapper {
	flex-shrink: 0;
}

.hospital-logo {
	width: 80px;
	height: 80px;
	border-radius: 12px;
	border: 2px solid #e5e7eb;
}

.hospital-logo-placeholder {
	width: 80px;
	height: 80px;
	border-radius: 12px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
}

.placeholder-icon {
	font-size: 40px;
}

.hospital-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.hospital-name {
	font-size: 22px;
	font-weight: 700;
	color: #1f2937;
}

.hospital-rating {
	display: flex;
	align-items: center;
	gap: 6px;
}

.rating-value {
	font-size: 18px;
	font-weight: 600;
	color: #3b82f6;
}

.rating-stars {
	font-size: 16px;
}

.rating-count {
	font-size: 13px;
	color: #6b7280;
	}

/* 医院详细信息 */
.hospital-body {
	padding: 24px;
	display: flex;
	flex-direction: column;
	gap: 24px;
}

.info-section {
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 8px;
	padding-bottom: 8px;
	border-bottom: 2px solid #3b82f6;
	}

.info-row {
		display: flex;
	align-items: flex-start;
	gap: 12px;
	padding: 8px 0;
	
	&.vertical {
		flex-direction: column;
	}
}

.info-label {
	font-size: 14px;
	color: #6b7280;
	min-width: 140px;
	flex-shrink: 0;
}

.info-value {
	flex: 1;
	font-size: 14px;
	color: #1f2937;
	word-break: break-all;
}

.tags-container {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.tag {
	padding: 4px 12px;
	background: #dbeafe;
	color: #1e40af;
	border-radius: 16px;
	font-size: 12px;
	font-weight: 500;
}

/* 操作按钮 */
.hospital-actions {
	display: flex;
	gap: 12px;
	padding: 20px 24px;
	border-top: 1px solid #e5e7eb;
	background: #f9fafb;
}

.btn {
	flex: 1;
	padding: 12px 20px;
	border-radius: 8px;
	border: none;
	cursor: pointer;
	font-size: 14px;
	font-weight: 500;
	transition: all 0.3s ease;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	gap: 6px;

	&.btn-primary {
		background-color: #3b82f6;
		color: white;

		&:active {
			background-color: #2563eb;
		}
	}

	&.btn-default {
		background-color: #e5e7eb;
		color: #374151;

		&:active {
			background-color: #d1d5db;
		}
	}

	&.btn-danger {
		background-color: #ef4444;
		color: white;

		&:active {
			background-color: #dc2626;
		}
	}

	&.btn-large {
		padding: 14px 28px;
		font-size: 16px;
	}
}

.icon {
	font-size: 16px;
}

/* 提示卡片 */
.tip-card {
	background: #f8fafc;
	border: 1px solid #e2e8f0;
	border-radius: 8px;
	padding: 16px;
	display: flex;
	gap: 12px;
}

.tip-icon {
	font-size: 20px;
	flex-shrink: 0;
	opacity: 0.6;
}

.tip-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.tip-title {
	font-size: 13px;
	font-weight: 600;
	color: #475569;
}

.tip-text {
	font-size: 12px;
	color: #64748b;
	line-height: 1.6;
}

/* 移动端响应式 */
@media (max-width: 768px) {
	.page-container {
		padding: 12px;
	}

	.page-header {
		padding: 16px;
	}

	.page-title {
		font-size: 20px;
	}

	.page-subtitle {
		font-size: 12px;
	}

	.hospital-header {
		flex-direction: column;
		align-items: flex-start;
		padding: 20px;
	}

	.hospital-logo {
		width: 60px;
		height: 60px;
	}

	.hospital-logo-placeholder {
		width: 60px;
		height: 60px;
	}

	.placeholder-icon {
		font-size: 30px;
	}

	.hospital-name {
		font-size: 18px;
	}

	.hospital-body {
		padding: 20px;
	}

	.info-label {
		min-width: 100px;
		font-size: 13px;
	}

	.info-value {
		font-size: 13px;
	}

	.hospital-actions {
		flex-direction: column;
		padding: 16px 20px;
	}

	.btn {
		width: 100%;
	}

	.tip-card {
		padding: 12px;
	}

	.tip-text {
		font-size: 12px;
	}
}
</style>
